
package uk.ac.cam.cl.oscar.MMS_server;

import uk.ac.cam.cl.oscar.*;

import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.FileInputStream;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.net.HttpURLConnection;
import java.net.URL;

public class SendMMS {
    
    private String rootDirectory = "c://thumbnails/";
    private String zipName;
    
    public void compileMMS(ImageRecord[] matches){
        try{
            long uniqueNo = Thread.currentThread().getId(); //Get unique number for thread
            int noImages = matches.length;
           
            /*Setup new directory for MMS - unique directory created using thread ID*/
            File directory = new File(String.format("%s%d", rootDirectory, uniqueNo));
            directory.mkdir();
            
            /*Delete any existing files within this directory*/
            File[] files = directory.listFiles();
            for(int i = 0; i < files.length; i++){
                files[i].delete();
            }
            
            /*Following Code adds files containing the MMS to the directory above and zips them
            into a single compressed file to be sent to the gateway*/
            
            /*Create manifest file for MMS*/
            File manifest = new File(String.format("%s%d/manifest", rootDirectory, uniqueNo));
            manifest.createNewFile();
            
            /*Open output stream to manifest file*/
            FileOutputStream manifest_fos = new FileOutputStream(manifest);
            PrintStream manifest_ps = new PrintStream(manifest_fos);
            
            /*Add lines to manifest file, order match entries according to score*/
            /*First order array in terms of score*/
            ImageRecord buffer;
            for(int j = 0; j < (noImages - 1); j++){
                if(noImages == 1) continue;
                for(int i = 0; i < noImages -1; i++){
                    buffer = matches[i];
                    if(matches[i].getScore() < matches[i+1].getScore()){
                        matches[i] = matches[i+1];
                        matches[i+1] = buffer;
                    }
                }
            }
            
            /*Add lines to manifest file*/
            for(int i =0; i < noImages; i++){
                manifest_ps.println(matches[i].getPosterId()+".jpg=image/jpeg");
                manifest_ps.println(matches[i].getPosterId()+".txt=text/plain");
            }
           
            /*Close file stream*/
            manifest_ps.close();
            
            /*Create text files containing text to go in MMS*/
            for(int i = 0; i < noImages; i++){
                /*Create text file*/
                File file = new File(String.format("%s%d/%s.txt", rootDirectory, uniqueNo, matches[i].getPosterId()));
                file.createNewFile();
                /*Open output stream*/
                FileOutputStream text_fos = new FileOutputStream(file);
                PrintStream text_ps = new PrintStream(text_fos);
                /*Write details to text file*/  
                String posterId = String.format("Poster ID: %s", matches[i].getPosterId());
                String artist = String.format("Artist: %s", matches[i].getArtist());
                String blurb = String.format("Blurb: %s", matches[i].getPosterBlurb());
                String cost = String.format("Cost: %s", matches[i].getCost());
                int scoreValue = (int)(matches[i].getScore()*100.0f);
                String score = String.format("Match: %d", scoreValue);
                score+="%";
                text_ps.println(posterId);
                text_ps.println(artist);
                text_ps.println(blurb);
                text_ps.println(cost);
                text_ps.println(score);
                /*Close output stream*/
                text_ps.close();
            }
           
            /*write required thumbnails to the unique directory*/
            for(int i = 0; i < noImages; i++){
                File file = new File(String.format("%s%d/%s.jpg", rootDirectory, uniqueNo, matches[i].getPosterId()));
                javax.imageio.ImageIO.write(matches[i].getThumbnail(), "jpeg", file);
            }
             
            /*Add directory contents to zip*/
            zipName = String.format("%d.zip", System.currentTimeMillis());
            
            /*Create a zipped output stream*/
            FileOutputStream zippedFile = new FileOutputStream(String.format("%s%d/%s", rootDirectory, uniqueNo, zipName));
            ZipOutputStream zippedOutput = new ZipOutputStream(new BufferedOutputStream(zippedFile));
            
            /*Get a list of directory contents to be zipped*/
            File uniqueDirectory = new File(String.format("%s%d", rootDirectory, uniqueNo));
            String[] directoryContents = uniqueDirectory.list();
            
            /*Loop through each file and add it to zip*/
            for(int i = 0; i < directoryContents.length; i++){
                /*Ignore zip file itself and standard Thumbs.db file*/
                if(directoryContents[i].equals("Thumbs.db")||directoryContents[i].equals(zipName)) continue;
                /*Create new entry in zip file*/
                ZipEntry entry = new ZipEntry(String.format("%s", directoryContents[i]));
                zippedOutput.putNextEntry(entry);
                /*Create input stream to read file*/
                FileInputStream manifestInput = new FileInputStream(String.format("%s%d/%s", rootDirectory, uniqueNo, directoryContents[i]));
                BufferedInputStream bufferedManifestInput = new BufferedInputStream(manifestInput);
                /*Read uncompressed data from input stream into compressed output stream*/
                while(bufferedManifestInput.available() > 0){
                    zippedOutput.write(bufferedManifestInput.read());
                }                
                /*Close input stream for this file*/
                bufferedManifestInput.close();
            }
            
            /*Close zipped output stream*/
            zippedOutput.close();
            
        }
        catch(IOException e){
            System.out.printf("IOException Occurred in CompileMMS()%n");
        }
       
    }
    
    public void send(String phoneNo){
        
        long uniqueID = Thread.currentThread().getId(); //Get ID of thread, corresponds to folder name in which MMS resides
        String serverAddress = "http://oscarpics.no-ip.org/"; //Domain name of server
        String userName = "skunkymonkey"; //User name for gateway
        String password = "asdfghjk1"; //Password for gateway
        String from = "60300"; //Phone number SMS will appear to be sent from
        
        try{
            
           /*Create URL to connect to with parameters*/
           String s = "http://www.itagg.com/smsg/itagg_mms_mt.php?user=" + userName + "&pass=" + password + "&to=" + phoneNo + "&from=" + from + "&url=" + serverAddress + uniqueID + "/" + zipName;
           URL url = new URL(s);
           System.out.printf("%s%n", s);
           
           /*Create HTTP connection to URL*/
           HttpURLConnection conn = (HttpURLConnection)url.openConnection();
           
           /*Set HHTP request to 'GET' and then connect to send message*/
           conn.setRequestMethod("GET");
           conn.setDoOutput(true);
           conn.connect();
           
           /*Read Response from server*/
           BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
           while(bis.available() > 0){
                System.out.printf("%c", bis.read());
           }
           
           System.out.printf("%n");
           bis.close();
           
        }
        catch(IOException e){
            System.out.printf("IOException Occurred in SendMMS.send()");
        }
        
    }
    

}
